<?php

namespace app\api\controller;

use app\common\model\MemberFile;
use hg\apidoc\annotation as Apidoc;
use hg\apidoc\annotation\Param;
use hg\apidoc\annotation\Query;
use hg\apidoc\annotation\Returned;
use hg\apidoc\annotation\Header;
use app\BaseController;
use think\facade\View;
use think\facade\Db;
use think\response\Json;
/**
 * 图片分类
 *
 * admin-ImgClass
 *
 * @Apidoc\Title("图片分类")
 * @Apidoc\Group("api")
 */
class ImgClass extends Auth
{

    /**
     * list
     * @Apidoc\Title("获取图片分类")
     */
    public function list(): \think\response\Json
    {
        $res = \app\common\model\ImgClass::where('member_id', $this->request->uid)->order('sort' ,'asc')->select();
        $res = $res->toArray();
        foreach ($res as $i => $item) {
            $item['count'] = MemberFile::where('img_class_id',$item['id'])->count();
            $item['name_all'] = $item['name'] . '(' . $item['count'] .')';
            $res[$i] = $item;
        }
        return success('ok', $res);
    }




    /**
     * @Apidoc\Title("新增")
     * @Param("name", type="varchar" ,desc="分类名称",require=true)
     * @Param("order", type="int", desc="排序",)
     * @Apidoc\Method("post")
     */
    public function add()
    {
        $data = request()->post(['name', 'sort']);
        validate([
            'name|分类名称' => 'require',
        ])->check($data);
        $data['member_id'] = $this->request->uid;
        \app\common\model\ImgClass::create($data);
        return success();
    }

    /**
     * delete
     * @Apidoc\Method("post")
     * @Param("id", type="int", desc="id",require=true)
     * @Apidoc\Title("删除")
     */
    public function delete()
    {
        $id = input('id');
        $imgClass = \app\common\model\ImgClass::find($id);
        if($imgClass['member_id'] != $this->request->uid) {
            return error('非法请求');
        }
        $find = MemberFile::where('img_class_id', $id)->find();
        if($find) {
            return error('该分类下有图片，不能删除');
        }
        \app\common\model\ImgClass::destroy($id);
        return success();
    }


    /**
     * update
     * @Apidoc\Title("修改")
     * @Param("name", type="varchar" ,desc="分类名称",require=true)
     * @Param("id", type="int", desc="id",require=true)
     * @Param("order", type="int", desc="排序")
     * @Apidoc\Method("post")
     */
    public function update()
    {
        $data = request()->post(['id', 'name', 'sort']);
        validate([
            'name|分类名称' => 'require',
            'id|分类id' => 'require',
        ])->check($data);
        $imgClass = \app\common\model\ImgClass::find($data['id']);
        if($imgClass['member_id'] != $this->request->uid) {
            return error('非法请求');
        }
        \app\common\model\ImgClass::update($data);
        return success($data);
    }
}
